#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
using namespace std;


int tickets = 1000;
//初始化全局锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//初始化全局变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* start_routine(void* args)
{
    string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);//线程阻塞挂起
        //判断暂时省略
        cout<<name<<" -> "<<tickets<<endl;
        tickets--;
        pthread_mutex_unlock(&mutex);
    }
}
// int main()
// {
//     // pthread_t t1,t2;
//     // pthread_create(&t1,nullptr,start_routine,(void*)"thread 1");
//     // pthread_create(&t1,nullptr,start_routine,(void*)"thread 2");



//     while(true)
//     {
//         sleep(1);
//         //pthread_cond_signal(&cond);//随机唤醒一个等待的线程
//         cout<<"main thread wakeup one thread..."<<endl;
//     }
//     // pthread_join(t1,nullptr);
//     // pthread_join(t2,nullptr);

//     return 0;
// }

int main()
{
#define NUM 5
    vector<pthread_t> tids(NUM);
    for(int i=0;i<NUM;++i)
    {
        char* namebuffer=new char[1024];
        snprintf(namebuffer,1024,"thread->%d",i+1);
        pthread_create(&tids[i],nullptr,start_routine,namebuffer);
    }
    while(true)
    {
        sleep(1);
        pthread_cond_broadcast(&cond);//唤醒全部等待的线程
        cout<<"main thread wakeup all thread..."<<endl;
    }
    for(const auto& tid:tids)
    {
        pthread_join(tid,nullptr);
    }
    return 0;
}